<template>
    <el-dialog v-model="visible" width="420px" :close-on-click-modal="false" :close-on-press-escape="true"
        style="border-radius: 15px;"
        class="overflow-hidden shadow-2xl backdrop-blur-xl bg-white/95 border border-white/20 animate-[dialogSlideIn_0.3s_cubic-bezier(0.34,1.56,0.64,1)]"
        :align-center="true" :show-close="true" :before-close="handleBeforeClose">
        <!-- 欢迎页面 -->
        <transition name="slide-fade" mode="out-in">
            <div v-if="currentStep === 'welcome'" class="text-center" key="welcome">
                <div class="mb-8">
                    <div class="flex items-center justify-center mb-2">
                        <div
                            class="text-2xl font-bold bg-gradient-to-r from-purple-600 to-blue-600 bg-clip-text text-transparent animate-[titleFadeIn_0.6s_ease-out]">
                            登录到 wyh's Blog
                        </div>
                        <span
                            class="text-3xl ml-2 cursor-pointer animate-[emojiBounce_2s_ease-in-out_infinite] drop-shadow-md hover:scale-110 hover:rotate-12 transition-all duration-300">
                            😘
                        </span>
                    </div>
                    <p class="text-sm text-gray-500 animate-[subtitleFadeIn_0.6s_ease-out_0.2s_both]">
                        欢迎回来! 请登录您的账号
                    </p>
                </div>

                <div>
                    <el-button type="primary" size="large"
                        class="w-full h-13 text-base font-semibold mb-5 rounded-xl bg-gradient-to-r from-purple-600 to-blue-600 border-none shadow-lg shadow-purple-500/30 hover:-translate-y-0.5 hover:shadow-xl hover:shadow-purple-500/40 active:translate-y-0 active:scale-95 transition-all duration-300 animate-[buttonSlideUp_0.6s_ease-out_0.4s_both]"
                        @click="switchToLogin">
                        <el-icon class="mr-2 text-lg">
                            <Message />
                        </el-icon>
                        通过邮箱 登录
                    </el-button>

                    <div class="relative text-center my-5 animate-[dividerFadeIn_0.6s_ease-out_0.6s_both]">
                        <div
                            class="absolute top-1/2 left-0 right-0 h-px bg-gradient-to-r from-transparent via-gray-300 to-transparent">
                        </div>
                        <span class="bg-white/95 px-4 text-sm text-gray-500 font-medium">
                            或通过社交账号登录
                        </span>
                    </div>

                    <div class="flex gap-3 animate-[socialButtonsSlideUp_0.6s_ease-out_0.8s_both]">
                        <el-button
                            class="flex-1 h-13 border-2 border-gray-200 bg-white/80 text-gray-600 rounded-xl font-semibold hover:border-gray-800 hover:text-gray-800 hover:-translate-y-0.5 hover:shadow-lg hover:shadow-gray-800/20 hover:scale-102 transition-all duration-300 backdrop-blur-sm"
                            @click="handleSocialLogin('github')">
                            <svg class="w-5 h-5 mr-2" viewBox="0 0 24 24" fill="currentColor">
                                <path
                                    d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
                            </svg>
                            GitHub
                        </el-button>

                        <el-button
                            class="flex-1 h-13 border-2 border-gray-200 bg-white/80 text-gray-600 rounded-xl font-semibold hover:border-blue-500 hover:text-blue-500 hover:-translate-y-0.5 hover:shadow-lg hover:shadow-blue-500/20 hover:scale-102 transition-all duration-300 backdrop-blur-sm"
                            @click="handleSocialLogin('google')">
                            <svg class="w-5 h-5 mr-2" viewBox="0 0 24 24" fill="currentColor">
                                <path
                                    d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                                <path
                                    d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                                <path
                                    d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
                                <path
                                    d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
                            </svg>
                            Google
                        </el-button>
                    </div>
                </div>
            </div>

            <!-- 登录表单 -->
            <div v-else-if="currentStep === 'login'" class="text-center" key="login">
                <div class="mb-8">
                    <div class="flex items-center justify-center mb-2">
                        <div
                            class="text-2xl font-bold bg-gradient-to-r from-purple-600 to-blue-600 bg-clip-text text-transparent animate-[titleFadeIn_0.6s_ease-out]">
                            登录到 wyh's Blog
                        </div>
                        <span
                            class="text-3xl ml-2 cursor-pointer animate-[emojiBounce_2s_ease-in-out_infinite] drop-shadow-md hover:scale-110 hover:rotate-12 transition-all duration-300">
                            😘
                        </span>
                    </div>
                    <p class="text-sm text-gray-500 animate-[subtitleFadeIn_0.6s_ease-out_0.2s_both]">
                        欢迎回来! 请登录您的账号
                    </p>
                </div>

                <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="0" class="space-y-4">
                    <el-form-item prop="email">
                        <el-input v-model="loginForm.email" placeholder="your@email.com" size="large"
                            class="rounded-xl border-2 border-gray-200 bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:shadow-lg hover:shadow-blue-500/10 focus-within:border-blue-500 focus-within:shadow-lg focus-within:shadow-blue-500/20 focus-within:-translate-y-0.5 transition-all duration-300" />
                    </el-form-item>

                    <el-form-item prop="password">
                        <el-input v-model="loginForm.password" type="password" placeholder="密码" size="large"
                            show-password
                            class="rounded-xl border-2 border-gray-200 bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:shadow-lg hover:shadow-blue-500/10 focus-within:border-blue-500 focus-within:shadow-lg focus-within:shadow-blue-500/20 focus-within:-translate-y-0.5 transition-all duration-300" />
                    </el-form-item>

                    <el-form-item prop="captchaCode">
                        <div class="flex gap-3">
                            <el-input v-model="loginForm.captchaCode" placeholder="输入验证码" size="large"
                                class="flex-1 rounded-xl border-2 border-gray-200 bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:shadow-lg hover:shadow-blue-500/10 focus-within:border-blue-500 focus-within:shadow-lg focus-within:shadow-blue-500/20 focus-within:-translate-y-0.5 transition-all duration-300" />
                            <div class="cursor-pointer border-2 border-gray-200 rounded-xl overflow-hidden bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:scale-102 hover:shadow-lg hover:shadow-blue-500/10 active:scale-95 transition-all duration-300"
                                @click="refreshCaptcha">
                                <img v-if="captchaImage" :src="captchaImage" alt="验证码" class="w-25 h-10 object-cover" />
                                <div v-else class="w-25 h-10 flex items-center justify-center text-gray-400">
                                    加载中...
                                </div>
                            </div>
                        </div>
                    </el-form-item>

                    <div class="text-right mb-5">
                        <el-link type="primary"
                            class="text-sm font-medium hover:translate-x-0.5 transition-all duration-300">
                            忘记密码? 点击这里重置
                        </el-link>
                    </div>

                    <el-form-item>
                        <div class="flex  w-full flex-1  gap-3">
                            <el-button type="primary" size="large"
                                class="w-full h-13 text-base font-semibold rounded-xl bg-gradient-to-r from-purple-600 to-blue-600 border-none shadow-lg shadow-purple-500/30 hover:-translate-y-0.5 hover:shadow-xl hover:shadow-purple-500/40 active:translate-y-0 active:scale-95 transition-all duration-300"
                                :loading="loading" @click="handleLogin">
                                登录
                            </el-button>
                            <el-button size="large"
                                class="w-full h-13 text-base font-semibold rounded-xl border-2 border-blue-500 text-blue-500 bg-white/80 backdrop-blur-sm hover:bg-blue-500 hover:text-white hover:-translate-y-0.5 hover:shadow-lg hover:shadow-blue-500/30 active:translate-y-0 active:scale-95 transition-all duration-300"
                                @click="switchToRegister">
                                没有账号? 注册
                            </el-button>
                        </div>
                    </el-form-item>
                </el-form>

                <div class="text-center mt-5">
                    <el-link type="primary"
                        class="text-sm font-medium hover:-translate-y-0.5 transition-all duration-300"
                        @click="switchToWelcome">
                        返回使用快捷登录
                    </el-link>
                </div>
            </div>

            <!-- 注册表单 -->
            <div v-else-if="currentStep === 'register'" class="text-center" key="register">
                <div class="mb-8">
                    <div class="flex items-center justify-center mb-2">
                        <div
                            class="text-2xl font-bold bg-gradient-to-r from-purple-600 to-blue-600 bg-clip-text text-transparent animate-[titleFadeIn_0.6s_ease-out]">
                            注册 wyh's Blog
                        </div>
                        <span
                            class="text-3xl ml-2 cursor-pointer animate-[emojiBounce_2s_ease-in-out_infinite] drop-shadow-md hover:scale-110 hover:rotate-12 transition-all duration-300">
                            😘
                        </span>
                    </div>
                    <p class="text-sm text-gray-500 animate-[subtitleFadeIn_0.6s_ease-out_0.2s_both]">
                        创建一个新账号,开始您的旅程
                    </p>
                </div>

                <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" label-width="0"
                    class="space-y-4">
                    <el-form-item prop="nickname">
                        <el-input v-model="registerForm.nickname" placeholder="您的昵称" size="large"
                            class="rounded-xl border-2 border-gray-200 bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:shadow-lg hover:shadow-blue-500/10 focus-within:border-blue-500 focus-within:shadow-lg focus-within:shadow-blue-500/20 focus-within:-translate-y-0.5 transition-all duration-300" />
                    </el-form-item>

                    <el-form-item prop="email">
                        <el-input v-model="registerForm.email" placeholder="your@email.com" size="large"
                            class="rounded-xl border-2 border-gray-200 bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:shadow-lg hover:shadow-blue-500/10 focus-within:border-blue-500 focus-within:shadow-lg focus-within:shadow-blue-500/20 focus-within:-translate-y-0.5 transition-all duration-300" />
                    </el-form-item>

                    <el-form-item prop="password">
                        <el-input v-model="registerForm.password" type="password" placeholder="密码" size="large"
                            show-password
                            class="rounded-xl border-2 border-gray-200 bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:shadow-lg hover:shadow-blue-500/10 focus-within:border-blue-500 focus-within:shadow-lg focus-within:shadow-blue-500/20 focus-within:-translate-y-0.5 transition-all duration-300" />
                    </el-form-item>

                    <el-form-item prop="confirmPassword">
                        <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码" size="large"
                            show-password
                            class="rounded-xl border-2 border-gray-200 bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:shadow-lg hover:shadow-blue-500/10 focus-within:border-blue-500 focus-within:shadow-lg focus-within:shadow-blue-500/20 focus-within:-translate-y-0.5 transition-all duration-300" />
                    </el-form-item>

                    <el-form-item prop="verificationCode">
                        <el-input v-model="registerForm.verificationCode" placeholder="邮箱验证码" size="large"
                            class="rounded-xl border-2 border-gray-200 bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:shadow-lg hover:shadow-blue-500/10 focus-within:border-blue-500 focus-within:shadow-lg focus-within:shadow-blue-500/20 focus-within:-translate-y-0.5 transition-all duration-300" />
                    </el-form-item>

                    <el-form-item prop="captchaCode">
                        <div class="flex gap-3">
                            <el-input v-model="registerForm.captchaCode" placeholder="图形验证码" size="large"
                                class="flex-1 rounded-xl border-2 border-gray-200 bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:shadow-lg hover:shadow-blue-500/10 focus-within:border-blue-500 focus-within:shadow-lg focus-within:shadow-blue-500/20 focus-within:-translate-y-0.5 transition-all duration-300" />
                            <div class="cursor-pointer border-2 border-gray-200 rounded-xl overflow-hidden bg-white/80 backdrop-blur-sm hover:border-blue-500 hover:scale-102 hover:shadow-lg hover:shadow-blue-500/10 active:scale-95 transition-all duration-300"
                                @click="refreshCaptcha">
                                <img v-if="captchaImage" :src="captchaImage" alt="验证码" class="w-25 h-10 object-cover" />
                                <div v-else class="w-25 h-10 flex items-center justify-center text-gray-400">
                                    加载中...
                                </div>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item>
                        <div class="flex  w-full flex-1 gap-3">
                            <el-button type="primary" size="large"
                                class="w-full h-13 text-base font-semibold rounded-xl bg-gradient-to-r from-purple-600 to-blue-600 border-none shadow-lg shadow-purple-500/30 hover:-translate-y-0.5 hover:shadow-xl hover:shadow-purple-500/40 active:translate-y-0 active:scale-95 transition-all duration-300"
                                :loading="loading" @click="handleRegister">
                                注册
                            </el-button>
                            <el-button size="large"
                                class="w-full h-13 text-base font-semibold rounded-xl border-2 border-blue-500 text-blue-500 bg-white/80 backdrop-blur-sm hover:bg-blue-500 hover:text-white hover:-translate-y-0.5 hover:shadow-lg hover:shadow-blue-500/30 active:translate-y-0 active:scale-95 transition-all duration-300"
                                @click="switchToLogin">
                                已有账号? 登录
                            </el-button>
                        </div>
                    </el-form-item>
                </el-form>

                <div class="text-center mt-5">
                    <el-link type="primary"
                        class="text-sm font-medium hover:-translate-y-0.5 transition-all duration-300"
                        @click="switchToWelcome">
                        返回使用快捷登录
                    </el-link>
                </div>
            </div>
        </transition>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Message } from '@element-plus/icons-vue'
import { login, register } from '@/api/user'
import { getCaptcha } from '@/api/common'

interface LoginForm {
    email: string
    password: string
    captchaCode: string
}

interface RegisterForm {
    nickname: string
    email: string
    password: string
    confirmPassword: string
    verificationCode: string
    captchaCode: string
}

const visible = ref(false)
const loading = ref(false)
const currentStep = ref<'welcome' | 'login' | 'register'>('welcome')
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()
const captchaImage = ref<string>('')
const captchaId = ref<string>('')

const loginForm = reactive<LoginForm>({
    email: '',
    password: '',
    captchaCode: ''
})

const registerForm = reactive<RegisterForm>({
    nickname: '',
    email: '',
    password: '',
    confirmPassword: '',
    verificationCode: '',
    captchaCode: ''
})

// 密码确认验证
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致'))
    } else {
        callback()
    }
}

const loginRules: FormRules = {
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    captchaCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ]
}

const registerRules: FormRules = {
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, validator: validateConfirmPassword, trigger: 'blur' }
    ],
    verificationCode: [
        { required: true, message: '请输入邮箱验证码', trigger: 'blur' }
    ],
    captchaCode: [
        { required: true, message: '请输入图形验证码', trigger: 'blur' }
    ]
}

// 获取验证码
const fetchCaptcha = async () => {
    try {
        const response = await getCaptcha()
        if (response.code === 200) {
            captchaImage.value = response.data.captchaImage
            captchaId.value = response.data.captchaId
        } else {
            ElMessage.error('获取验证码失败')
        }
    } catch (error) {
        ElMessage.error('获取验证码失败，请重试')
    }
}

// 刷新验证码
const refreshCaptcha = () => {
    fetchCaptcha()
}

// 打开对话框
const open = () => {
    visible.value = true
    currentStep.value = 'welcome'
    resetForms()
}

// 关闭对话框
const close = () => {
    visible.value = false
    currentStep.value = 'welcome'
    resetForms()
}

// 关闭前处理
const handleBeforeClose = (done: () => void) => {
    // 重置状态
    currentStep.value = 'welcome'
    resetForms()
    // 添加关闭动画
    setTimeout(() => {
        done()
    }, 200)
}

// 重置表单
const resetForms = () => {
    loginForm.email = ''
    loginForm.password = ''
    loginForm.captchaCode = ''
    registerForm.nickname = ''
    registerForm.email = ''
    registerForm.password = ''
    registerForm.confirmPassword = ''
    registerForm.verificationCode = ''
    registerForm.captchaCode = ''
    loginFormRef.value?.clearValidate()
    registerFormRef.value?.clearValidate()
}

// 切换到登录
const switchToLogin = () => {
    currentStep.value = 'login'
    fetchCaptcha()
}

// 切换到注册
const switchToRegister = () => {
    currentStep.value = 'register'
    fetchCaptcha()
}

// 切换到欢迎页面
const switchToWelcome = () => {
    currentStep.value = 'welcome'
}

// 处理登录
const handleLogin = async () => {
    if (!loginFormRef.value) return

    try {
        await loginFormRef.value.validate()
        loading.value = true

        // 调用登录接口
        const response = await login({
            email: loginForm.email,
            password: loginForm.password,
            captchaCode: loginForm.captchaCode
        })

        if (response.code === 200) {
            close()
            emit('login-success', response)
        } else {
            ElMessage.error(response.message)
        }
    } catch (error: any) {
        if (error.response?.data?.message) {
            ElMessage.error(error.response.data.message)
        } else {
            ElMessage.error('登录失败，请重试')
        }
    } finally {
        loading.value = false
    }
}

// 处理注册
const handleRegister = async () => {
    if (!registerFormRef.value) return

    try {
        await registerFormRef.value.validate()
        loading.value = true

        // 调用注册接口
        const response = await register({
            email: registerForm.email,
            password: registerForm.password,
            nickname: registerForm.nickname,
            verificationCode: registerForm.verificationCode,
            captchaCode: registerForm.captchaCode
        })
        if (response.code === 200) {
            close()
            emit('register-success', response)
        } else {
            ElMessage.error(response.message)
        }

    } catch (error: any) {
        if (error.response?.data?.message) {
            ElMessage.error(error.response.data.message)
        } else {
            ElMessage.error('注册失败，请重试')
        }
    } finally {
        loading.value = false
    }
}

// 处理社交账号登录
const handleSocialLogin = (provider: 'github' | 'google') => {
    ElMessage.info(`${provider} 登录功能开发中...`)
}

// 处理忘记密码
const handleForgotPassword = () => {
    ElMessage.info('忘记密码功能开发中...')
}

// 定义事件
const emit = defineEmits<{
    'login-success': [data: any]
    'register-success': [data: any]
}>()

// 暴露方法
defineExpose({
    open,
    close
})

// 组件挂载时不需要获取验证码，等用户切换到登录或注册页面时再获取
</script>

<style scoped>
:deep(.el-dialog) {
    border-radius: 20px;
}

/* 内容切换动画 */
.slide-fade-enter-active,
.slide-fade-leave-active {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.slide-fade-enter-from {
    opacity: 0;
    transform: translateX(30px);
}

.slide-fade-leave-to {
    opacity: 0;
    transform: translateX(-30px);
}

/* 动画关键帧 */
@keyframes dialogSlideIn {
    0% {
        opacity: 0;
        transform: scale(0.8) translateY(-20px);
    }

    100% {
        opacity: 1;
        transform: scale(1) translateY(0);
    }
}

@keyframes titleFadeIn {
    0% {
        opacity: 0;
        transform: translateY(-20px);
    }

    100% {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes subtitleFadeIn {
    0% {
        opacity: 0;
        transform: translateY(-10px);
    }

    100% {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes buttonSlideUp {
    0% {
        opacity: 0;
        transform: translateY(20px);
    }

    100% {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes dividerFadeIn {
    0% {
        opacity: 0;
        transform: scaleX(0);
    }

    100% {
        opacity: 1;
        transform: scaleX(1);
    }
}

@keyframes socialButtonsSlideUp {
    0% {
        opacity: 0;
        transform: translateY(20px);
    }

    100% {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes emojiBounce {

    0%,
    100% {
        transform: translateY(0) scale(1);
    }

    50% {
        transform: translateY(-3px) scale(1.1);
    }
}

/* 响应式设计 */
@media (max-width: 480px) {
    .el-dialog {
        width: 90% !important;
        margin: 20px auto;
    }

    .el-dialog__body {
        padding: 0 20px 20px;
    }

    .text-2xl {
        font-size: 1.25rem;
    }

    .flex {
        flex-direction: column;
    }

    .gap-3 {
        gap: 0.5rem;
    }
}
</style>